<template>
  <div class="after-sale-detail">
    <div class="page-header">
      <h2>售后详情</h2>
      <el-button @click="goBack">返回列表</el-button>
    </div>

    <div class="detail-content" v-loading="loading">
      <el-card class="detail-card">
        <!-- 售后状态进度条 -->
        <div class="status-progress">
          <el-steps :active="getStepActive(afterSaleInfo.status)" finish-status="success">
            <el-step title="提交申请" :description="formatDate(afterSaleInfo.createTime)"></el-step>
            <el-step title="商家处理" :description="afterSaleInfo.handleTime ? formatDate(afterSaleInfo.handleTime) : '处理中'"></el-step>
            <el-step title="完成" :description="getCompletionDesc()"></el-step>
          </el-steps>
        </div>

        <!-- 售后基本信息 -->
        <el-descriptions title="基本信息" :column="2" border>
          <el-descriptions-item label="售后单号">{{ afterSaleInfo.afterSaleNo }}</el-descriptions-item>
          <el-descriptions-item label="关联订单号">{{ afterSaleInfo.orderNo }}</el-descriptions-item>
          <el-descriptions-item label="申请时间">{{ formatDate(afterSaleInfo.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="售后状态">
            <el-tag :type="getStatusType(afterSaleInfo.status)">
              {{ getStatusText(afterSaleInfo.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="售后类型">
            <el-tag :type="getTypeTag(afterSaleInfo.type)">
              {{ getTypeText(afterSaleInfo.type) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="申请原因">{{ afterSaleInfo.reason }}</el-descriptions-item>
          <el-descriptions-item label="问题描述" :span="2">{{ afterSaleInfo.description }}</el-descriptions-item>
        </el-descriptions>

        <!-- 商品信息 -->
        <div class="section-title">商品信息</div>
        <el-table :data="afterSaleInfo.items || []" border style="width: 100%">
          <el-table-column label="商品信息" min-width="300">
            <template #default="{ row }">
              <div class="goods-info">
                <el-image :src="row.image" class="goods-image"></el-image>
                <div class="goods-detail">
                  <div class="goods-name">{{ row.itemName }}</div>
                  <div class="goods-spec">{{ row.specs || '默认规格' }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="price" label="单价" width="120">
            <template #default="{ row }">
              ¥{{ formatPrice(row.price) }}
            </template>
          </el-table-column>
          <el-table-column prop="quantity" label="数量" width="100"></el-table-column>
          <el-table-column label="小计" width="120">
            <template #default="{ row }">
              ¥{{ formatPrice(row.price * row.quantity) }}
            </template>
          </el-table-column>
        </el-table>

        <!-- 凭证照片 -->
        <div v-if="afterSaleInfo.images && afterSaleInfo.images.length > 0" class="evidence-section">
          <div class="section-title">凭证照片</div>
          <div class="images-container">
            <el-image
              v-for="(img, index) in afterSaleInfo.images"
              :key="index"
              :src="img"
              :preview-src-list="afterSaleInfo.images"
              fit="cover"
              class="evidence-image"
            ></el-image>
          </div>
        </div>

        <!-- 处理结果 -->
        <div v-if="afterSaleInfo.status !== 'PENDING'" class="result-section">
          <div class="section-title">处理结果</div>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="处理结果">
              <el-tag :type="afterSaleInfo.status === 'APPROVED' ? 'success' : 'danger'">
                {{ afterSaleInfo.status === 'APPROVED' ? '已同意' : '已拒绝' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="处理时间">{{ formatDate(afterSaleInfo.handleTime) }}</el-descriptions-item>
            <el-descriptions-item label="处理备注">{{ afterSaleInfo.remark || '无' }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 操作按钮 -->
        <div class="action-section">
          <el-button v-if="afterSaleInfo.status === 'PENDING'" type="danger" @click="cancelAfterSale">取消申请</el-button>
          <el-button v-if="afterSaleInfo.status === 'APPROVED' && afterSaleInfo.type !== 'REFUND'" type="primary" @click="showLogistics">填写物流信息</el-button>
        </div>
      </el-card>
    </div>

    <!-- 物流信息对话框 -->
    <el-dialog
      v-model="logisticsDialogVisible"
      title="填写物流信息"
      width="500px"
    >
      <el-form ref="logisticsFormRef" :model="logisticsForm" :rules="logisticsRules" label-width="100px">
        <el-form-item label="物流公司" prop="company">
          <el-select v-model="logisticsForm.company" placeholder="请选择物流公司" style="width: 100%">
            <el-option label="顺丰速运" value="SF"></el-option>
            <el-option label="中通快递" value="ZTO"></el-option>
            <el-option label="圆通快递" value="YTO"></el-option>
            <el-option label="韵达快递" value="YD"></el-option>
            <el-option label="申通快递" value="STO"></el-option>
            <el-option label="京东物流" value="JD"></el-option>
            <el-option label="其他" value="OTHER"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="物流单号" prop="trackingNo">
          <el-input v-model="logisticsForm.trackingNo" placeholder="请输入物流单号"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            v-model="logisticsForm.remark"
            placeholder="可选填"
            :rows="3"
          ></el-input>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="logisticsDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitLogistics" :loading="submitting">提交</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import service from '@/utils/request'

const route = useRoute()
const router = useRouter()
const afterSaleId = route.params.id

const loading = ref(false)
const submitting = ref(false)
const logisticsDialogVisible = ref(false)
const afterSaleInfo = ref({})

// 物流信息表单
const logisticsForm = reactive({
  company: '',
  trackingNo: '',
  remark: ''
})

// 物流表单验证规则
const logisticsRules = {
  company: [{ required: true, message: '请选择物流公司', trigger: 'change' }],
  trackingNo: [{ required: true, message: '请输入物流单号', trigger: 'blur' }]
}

// 获取售后详情
const getAfterSaleDetail = async () => {
  loading.value = true
  try {
    const res = await service.get(`/user/after_sale/${afterSaleId}`)
    if (res) {
      afterSaleInfo.value = res
    }
  } catch (error) {
    console.error('获取售后详情失败:', error)
    ElMessage.error('获取售后详情失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 返回列表
const goBack = () => {
  router.push('/user/after_sale')
}

// 取消售后申请
const cancelAfterSale = async () => {
  try {
    await ElMessageBox.confirm('确认取消此售后申请？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    await service.post(`/user/after_sale/${afterSaleId}/cancel`)
    ElMessage.success('售后申请已取消')
    getAfterSaleDetail() // 刷新数据
  } catch (error) {
    if (error === 'cancel') return
    console.error('取消售后申请失败:', error)
    ElMessage.error('取消售后申请失败，请稍后重试')
  }
}

// 显示物流信息对话框
const showLogistics = () => {
  logisticsDialogVisible.value = true
}

// 提交物流信息
const submitLogistics = async () => {
  const logisticsFormRef = ref(null)
  
  try {
    await logisticsFormRef.value.validate()
    
    submitting.value = true
    
    await service.post(`/user/after_sale/${afterSaleId}/logistics`, logisticsForm)
    
    ElMessage.success('物流信息提交成功')
    logisticsDialogVisible.value = false
    getAfterSaleDetail() // 刷新数据
    
  } catch (error) {
    console.error('提交物流信息失败:', error)
    ElMessage.error('提交物流信息失败，请稍后重试')
  } finally {
    submitting.value = false
  }
}

// 获取进度条活跃步骤
const getStepActive = (status) => {
  const statusMap = {
    'PENDING': 1,
    'APPROVED': 2,
    'REJECTED': 2,
    'CLOSED': 3
  }
  return statusMap[status] || 0
}

// 获取完成描述
const getCompletionDesc = () => {
  if (afterSaleInfo.value.status === 'CLOSED') {
    return '已完成'
  }
  if (afterSaleInfo.value.status === 'REJECTED') {
    return '已拒绝'
  }
  return '处理中'
}

// 获取状态类型
const getStatusType = (status) => {
  const typeMap = {
    'PENDING': 'warning',
    'APPROVED': 'success',
    'REJECTED': 'danger',
    'CLOSED': 'info'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const textMap = {
    'PENDING': '处理中',
    'APPROVED': '已通过',
    'REJECTED': '已拒绝',
    'CLOSED': '已关闭'
  }
  return textMap[status] || '未知状态'
}

// 获取售后类型标签
const getTypeTag = (type) => {
  const typeMap = {
    'REFUND': 'danger',
    'EXCHANGE': 'warning',
    'RETURN': 'info'
  }
  return typeMap[type] || 'info'
}

// 获取售后类型文本
const getTypeText = (type) => {
  const textMap = {
    'REFUND': '仅退款',
    'EXCHANGE': '换货',
    'RETURN': '退货退款'
  }
  return textMap[type] || '未知类型'
}

// 格式化价格
const formatPrice = (price) => {
  return Number(price).toFixed(2)
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '暂无'
  try {
    const d = new Date(date)
    return d.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  } catch (error) {
    return '日期格式错误'
  }
}

onMounted(() => {
  getAfterSaleDetail()
})
</script>

<style scoped>
.after-sale-detail {
  width: 100%;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  font-size: 20px;
  margin: 0;
  color: var(--text-regular);
}

.detail-card {
  margin-bottom: 20px;
}

.status-progress {
  margin-bottom: 30px;
}

.section-title {
  margin: 20px 0 10px;
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  border-left: 3px solid var(--primary-color);
  padding-left: 10px;
}

.goods-info {
  display: flex;
  align-items: center;
}

.goods-image {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  margin-right: 15px;
}

.goods-detail {
  flex: 1;
}

.goods-name {
  font-size: 14px;
  color: var(--text-regular);
  margin-bottom: 5px;
}

.goods-spec {
  font-size: 12px;
  color: var(--text-secondary);
}

.evidence-section {
  margin-top: 20px;
}

.images-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin: 10px 0;
}

.evidence-image {
  width: 100px;
  height: 100px;
  border-radius: 4px;
  object-fit: cover;
  cursor: pointer;
}

.result-section {
  margin-top: 20px;
}

.action-section {
  margin-top: 30px;
  display: flex;
  justify-content: center;
  gap: 20px;
}
</style> 